<?php
/**
 * [woniu] Copyright (c) 2016/8/18
 * join.ctrl
 * 报名入口控制器
 */

defined('IN_IA') or exit('Access Denied');
if (empty($_W['fans']['nickname'])){
    $_W['fans'] = getInfo();
}
$op = !empty($_GPC['op']) ? $_GPC['op'] : 'display';
$pagetitle = '报名信息填写';
$activityid        = intval($_GPC['activityid']);
$activity          = model_activity::getSingleActivity($activityid, '*');
$proid          = intval($_GPC['proid']);
$teamnum           = intval($_GPC['teamnum']) ? intval($_GPC['teamnum']) : 1;
$form              = unserialize($activity['form']);//系统表单
$activity['prize'] = unserialize($activity['prize']);//积分
if ($_SESSION['status']!='login'){
    include $this->template ('aitimt/login');
    exit;
}
if ($_W['container']!='wechat'){
    aide_message('请用微信打开此链接接报名', '', 'error', '点确定返回');
}
if ($activity['is_show']==0 || $activity['review']!=1){
    aide_message('当前活动没有开放报名', '', 'error', '点确定返回');
}
if ($_W['_config']['guanzhu_join']==2 && empty($_W['fans']['follow'])){
    aide_message('您还未关注,不能报名', app_url('activity/detail/display', array ('activityid' => $activityid)), 'warning');
}

$blacklist = pdo_get('aide_member_blacklist', array('uid' => $_W['member']['uid']), array('uid'));
if ($blacklist['uid']){
    aide_message('对不起您被主办方屏蔽了', app_url('activity/detail/display', array ('activityid' => $activityid)), 'error','请联系主办方解封');
}
if ($activity['costcredit'] && $activity['costcredit'] > $_W['member']['credit1']){
    aide_message('对不起您的积分不足', '', 'error', '参与当前活动需要 '.$activity['costcredit'].' 积分，分享当前活动可以赚取积分哦！');
}
if (!is_array($form['realname'])){//表单优化，数据兼容
    $sysform['realname']['title'] = $form['realname'];
    $sysform['realname']['need'] = 1;
    $sysform['realname']['show'] = $form['realnameshow'];

    $sysform['mobile']['title'] = $form['mobile'];
    $sysform['mobile']['need'] = 1;
    $sysform['mobile']['show'] = $form['mobileshow'];

    $sysform['gender']['title'] = $form['gender'];
    $sysform['gender']['need'] = $form['gendermust'];
    $sysform['gender']['show'] = $form['gendershow'];

    $sysform['birthyear']['title'] = $form['birthyear'];
    $sysform['birthyear']['need'] = $form['birthmust'];
    $sysform['birthyear']['show'] = $form['birthshow'];

    $sysform['resideprovince']['title'] = $form['resideprovince'];
    $sysform['resideprovince']['need'] = $form['residemust'];
    $sysform['resideprovince']['show'] = $form['resideshow'];
}else{
    $sysform = $form;
    $sysform['realname']['show'] = $form['realname']['show']=='' || $form['realname']['show']?1:0;
    $sysform['mobile']['show'] = $form['mobile']['show']=='' || $form['mobile']['show']?1:0;
    if (count($sysform)>2){
        $sysform['gender']['show'] = $form['gender']['show']=='' || $form['gender']['show']?1:0;
        $sysform['birthyear']['show'] = $form['birthyear']['show']=='' || $form['birthyear']['show']?1:0;
        $sysform['resideprovince']['show'] = $form['resideprovince']['show']=='' || $form['resideprovince']['show']?1:0;
    }
}
//验证名额，每次进入加载剩余名额数量、及规格
$condition = " activityid = $activityid and status <> 5 and (status <> 0 or paytype = 'delivery')";
$quota = $activity['quota'];

$prodata=pdo_fetchall("SELECT * FROM " . tablename('aide_activity_pro') . " WHERE id=$proid  ORDER BY  id ASC");
$activity['aprice'] = $prodata[0]['pprice'];
$quota = $prodata[0]['sum'];
$price = $activity['aprice'];
$pay_price = $activity['aprice'];
$condition = "uniacid={$_W['uniacid']} and activityid = $activityid and status <> 5 and (status <> 0 or paytype = 'delivery')";
$condition.= $proid ? " and pid = $proid" :'';
$joinnum = pdo_fetchcolumn("SELECT SUM(teamnum) FROM " . tablename('aide_activity_records') . " WHERE $condition");
$joinnum = $joinnum?$joinnum:0;

if ($_W['plugin']['card']['config']['card_enable'] && $yearcard['buy']) {//年卡
    if ($activity['atype']==2){
        if (!$activity['prize']['cardper']['enable']){//年卡价格
            //$price = $activity['marketprice'];
            $vipdeduct = $activity['aprice'] - $activity['marketprice'];
            $pay_price = $activity['marketprice'];
        }else {//年卡打折
            $yc['percent'] = $activity['prize']['cardper']['percent'];
        }
    }
    if ($_W['plugin']['card']['config']['credit_double']) $credit_double = 1;
}

$dc = $_GPC['dc'] == 'yes' ? TRUE : FALSE; //是否积分抵扣
$pay_price = sprintf("%.2f", $pay_price * $teamnum);
$afterMarketing = model_records::getafterMarketing($pay_price, $teamnum, $activityid, $dc, $yc); //获取优惠后的价格等参数
$pay_price = $afterMarketing['pay_price'];  //营销后的价格
$vipdeduct = empty($vipdeduct) ? $afterMarketing['cardReduce'] : $vipdeduct; //高级vip优惠费用

if($_W['isajax'] && $op == 'getprice') {
    $params = array(
        'price' =>$price,
        'pay_price' =>$pay_price,
        'joinnum' =>$joinnum,
        'm1' =>$afterMarketing['m1'],
        'm2' =>$afterMarketing['m2'],
        'm3' =>$afterMarketing['m3'],
        'm4' =>$afterMarketing['m4'],
        'max'=>$afterMarketing['max'],
        'p'=>$afterMarketing['p'],
        'deductMoney'=>$afterMarketing['deductMoney'],
        'deductCredit'=>$afterMarketing['deductCredit'],
        'orderMarket'=>$afterMarketing['orderMarket'],
        'cardReduce'=>$afterMarketing['cardReduce'],
        'token'=>$_W['token']
    );

    die(json_encode(array('errno'=>0, 'params'=>$params)));
}

if($op =='display'){
    load()->model('mc');
    $marketing = model_activity::getMarketing($activityid);//优惠
    $openid=$_W['fans']['openid'];
    $commendList= pdo_fetchall("SELECT id,remarks FROM " . tablename('aide_form_data_common') . " WHERE openid='$openid' AND status>0 AND uniacid='{$_W['uniacid']}' ORDER BY  id DESC");
    $cid=(int)$_GPC['cid'];
    if (!empty((int)$_GPC['recordid'])){
        $rid=(int)$_GPC['recordid'];
        if ($cid!=null){
            $temp   = pdo_fetchall("SELECT * FROM " . tablename('aide_form_data_common') . " WHERE id=$cid ORDER BY id DESC limit 1");
        }else{
            $temp   = pdo_fetchall("SELECT * FROM " . tablename('aide_form_data_common') . " WHERE rid=$rid ORDER BY rid DESC limit 1");
        }
        $profile=$temp[0];
        $test = pdo_fetchall("SELECT * FROM " . tablename('aide_activity_records') . " WHERE id=$rid ORDER BY  id DESC limit 1");
        $record=$test[0];
        $facename=$record['imageno'];
        $tempface=pdo_fetchall("SELECT * FROM " . tablename('aide_faceimg') . " WHERE file_name=$facename ORDER BY  id DESC");
        $faceid=$tempface[0]['id'];
    }else{
        $temp   = pdo_fetchall("SELECT * FROM " . tablename('aide_form_data_common') . " WHERE id=$cid ORDER BY id DESC  LIMIT 1 ");
        $profile=$temp[0];
    }
    $activityForm = model_activity::getNumActivityForm($activityid,'app');//读取表单
    $condition = "pid = $proid and openid='{$_W['openid']}'";
    $findUser = pdo_fetch("SELECT id FROM " . tablename ('aide_activity_records') . " WHERE $condition");

    if($joinnum >= $quota && $quota>0) {
        aide_message ('很遗憾！名额已经满了', app_url('activity/detail/display', array ('activityid' => $activityid)), 'warning');
    }
    $is_back=$_GPC['is_back'];
    include $this->template ('aitimt/join');
    exit;
}
if($_W['isajax'] && $op == 'join') {
    setcookie("sms_code", '');
    $data_member = $_GPC['member'];
    if (empty($data_member['realname']) && $systemform['realnameshow']) {
        aide_message ('请输入姓名','history.go(-1)','warning');
    }
    if (empty($data_member['mobile']) && $systemform['mobileshow']) {
        aide_message ('请输入手机','history.go(-1)','warning');
    }

    $_W['member'] = getMember($_W['openid']);
    if($dc == 'yes'){
        $deduct[0] = $afterMarketing['orderMarket']['deduct'][0];
        $deduct[1] = $afterMarketing['orderMarket']['deduct'][1];
        $orderMarket['deduct'] = $deduct;
    }

    if($credit_double) $orderMarket['credit_double'] = $credit_double;
    //此处有bug?支付金额错误？支付金额需大于0元？
    $price_temp = $pay_price = floatval($pay_price);
    if ($price_temp > 0){
        $orderMarket['market_price'] =  sprintf("%.2f", $price * $teamnum - $pay_price);
    }
    $data = array (
        'uid' => (int)$_W['member']['uid'],
        'activityid' => $activityid,
        'uniacid' => (int)$_W['uniacid'],
        'openid' =>(string)$_W['openid'],
        'teamnum' => $teamnum,
        'nickname' => (string)$_W['member']['nickname'],
        'headimgurl' => (string)$_W['member']['avatar'],
        'orderno' => createUniontid(),
        'realname' => (string)$data_member['realname'],
        'mobile' => (string)$data_member['mobile'],
        'gender' => (int)$_GPC['gender']==0 ? '保密' : ($_GPC['gender']==1?'男':'女'),
        'pic' => (string)$data_member['pic'],
        'msg' => htmlspecialchars_decode($_GPC['msg']),
        'pid' => $proid?$proid:0,
        'review' => (int)$activity['hasreview']?0:1,
        'status' => 2,
        'merchantid' => $activity['merchantid']?$activity['merchantid']:0,
        'marketing' => serialize($orderMarket)
    );

    if ($pay_price > 0){//获取付费金额
        $data['price'] = $pay_price;
        $data['aprice'] = $price;
        $data['vipdeduct'] = $vipdeduct;
        $data['status'] = 0;
    }
    /*处理检录图片0*/
    if($activity['has_record_image'] == 1){
        $faceimg_id = $_GPC['faceimg_id'];
        if(!($faceimg_id>0)){
            die(json_encode(array('errno' => 1, 'errmsg'=>'请上传人脸')));
            exit;
        }
        $condition = array(
            'uniacid' => $_W['uniacid'],
            'activityid' => $activity['id'],
            'openid' => $_W['openid'],
            'id' => $faceimg_id
        );
        $faceimg = pdo_get('aide_faceimg', $condition);
        if(!$faceimg){
            die(json_encode(array('errno' => 1, 'errmsg'=>'人脸录入失败，请联系管理员')));
            exit;
        }
        $data['imageurl'] = $faceimg['file_path'];
        $data['imageno'] = $faceimg['file_name'];
        //以下是获取公众号图片，不需要用了
        //        $data['imageurl'] = '';
        //        $data['serverids'] = $_GPC['serverIds'];
        //        if(!empty($_GPC['serverIds'])){
        //            $media_id = $_GPC['serverIds']; //单图
        //            $account_api = WeAccount::create();
        //            $account_api->clearAccessToken();
        //            $access_token = $account_api->getAccessToken();
        //            $newurl = "http://file.api.weixin.qq.com/cgi-bin/media/get" . "?access_token=" . $access_token . "&media_id=" . $media_id;//用php去请求获取微信图片的接口
        //            $filebody = file_get_contents($newurl); //通过接口获取图片流
        //            $uniqid = substr(time(),2,10).str_pad(rand(0,99),2,'0',STR_PAD_LEFT);
        //            $filename = $uniqid . '.jpg'; //定义图片名字及格式
        //            $imageurl = MODULE_ROOT . '/uploadfile/' . $_W['uniacid'] . '/' . $filename;
        //            file_put_contents($imageurl, $filebody);
        //            $data['imageurl'] = '/addons/aide_activity/uploadfile/' . $_W['uniacid'] . '/' . $filename;
        //            $data['imageno'] = $uniqid;
        //            $data['notes'] = $filebody . '-' . $access_token; //调试用
        //        }
    }
    /*处理检录图片1*/
    $condition = "pid = $proid and status > 0 and openid='{$_W['openid']}'";
    $findUser = pdo_fetch("SELECT id FROM " . tablename ('aide_activity_records') . " WHERE $condition");
    if(!empty($findUser) && !$activity['hasjoin']){
        if($_W['isajax']){
            die(json_encode(array('errno' => 1, 'errmsg'=>'你已经报名成功')));
            exit;
        }else{
            die(json_encode(array('errno' => 1, 'errmsg'=>'不能重复报名')));
            exit;
        }
    }else{
        if ($quota>0){
            $joinnum = model_records::getJoinNum($activityid, $proid) + $activity['falsenum'];
            if($joinnum >= $quota) {
                die(json_encode(array('errno' => 1, 'errmsg'=>'很遗憾！名额已经满了')));
                exit;
            }elseif($joinnum + $teamnum > $quota){
                die(json_encode(array('errno' => 1, 'errmsg'=>"活动仅剩 " . ($quota - $joinnum) . " 个名额")));
                exit;
            }
        }
        if (empty($_GPC['recordid'])){
            $result = pdo_insert('aide_activity_records', $data);
            $recordid=pdo_insertid();
        }else{
            $result ='update';
            pdo_update('aide_activity_records',$data,['id'=>$_GPC['recordid']]);
            $recordid=$_GPC['recordid'];
        }
        if (!empty($result)){
            //保存自定义表单信息
            $form_ids = $_GPC['form_id'];
            $len = count($form_ids);
            $form_items = array();
            for ($k = 0; $k < $len; $k++) {
                $form_items[$k] = is_array($_GPC["form_item_val_".$k]) ? implode(',', $_GPC["form_item_val_".$k]) : $_GPC["form_item_val_".$k];
                $form_id = $form_ids[$k];
                $a = array(
                    "activityid" => $activityid,
                    "recordid" => $recordid,
                    "formid" => $form_id,
                    "data" => $form_items[$k]
                );
                if (empty($_GPC['recordid'])){
                    pdo_insert("aide_form_data", $a);
                }else{
                    pdo_update('aide_form_data', ["activityid" => $activityid, "recordid" => $recordid, "data" => $form_items[$k]],['formid'=>$form_id]);
                }
                //表单数据
            }
            //同步会员信息
            if (!empty($_GPC['gender']))
            {
                $data_member['gender'] = $_GPC['gender'];
            }
            if (!empty($_GPC['birth']))
            {
                $data_member['birthyear'] = $_GPC['birth']['year'];
                $data_member['birthmonth'] = $_GPC['birth']['month'];
                $data_member['birthday'] = $_GPC['birth']['day'];
            }
            if (!empty($_GPC['reside']))
            {
                $data_member['resideprovince'] = $_GPC['reside']['province'];
                $data_member['residecity'] = $_GPC['reside']['city'];
                $data_member['residedist'] = $_GPC['reside']['district'];
            }
            if ($_GPC['education']!='') $data_member['education'] = $_GPC['education'];
            if ($_GPC['constellation']!='') $data_member['constellation'] = $_GPC['constellation'];
            if ($_GPC['zodiac']!='') $data_member['zodiac'] = $_GPC['zodiac'];
            if ($_GPC['bloodtype']!='') $data_member['bloodtype'] = $_GPC['bloodtype'];

            if (empty($_W['member']['mobile'])){
                mc_update($_W['member']['uid'], $data_member);
            }
            //插入常用表单数据
            $data_member['rid'] = $recordid;
            $data_member['uniacid'] = $_W['uniacid'];
            $data_member['openid'] = $_W['openid'];
            $data_member['avatar'] = $data_member['pic'];
            unset($data_member['pic']);
            if (empty($_GPC['recordid'])){
                pdo_insert('aide_form_data_common', $data_member);
            } else{
                pdo_update('aide_form_data_common', $data_member,['rid'=>$_GPC['recordid']]);
            }

            if ($pay_price > 0){//判断是否为付费活动
                die(json_encode(array('errno' => 0,'recordid' => $recordid, 'is_pay' => 1)));
                exit;
            }else{
                //积分变更
                aide_load()->model('credit');
                if ($_W['_config']['creditstatus'] == 1){
                    if ($activity['prize']['credit'] > 0){
                        $credit = $credit_double ? $activity['prize']['credit'] * 2 : $activity['prize']['credit'];
                        $credit_result = credit_update_credit1($_W['member']['uid'], $credit, "参与活动奖励：增加" . $credit . '积分', $activity['merchantid']);
                    }
                    if($dc == 'yes'){
                        credit_update_credit1($_W['member']['uid'], -1 * $deduct[0], "积分抵扣：减少" . $deduct[0] . '积分', $activity['merchantid']);
                    }
                    if($activity['costcredit']){
                        credit_update_credit1($_W['member']['uid'], -1 * $activity['costcredit'], "参与活动消耗：减少" . $activity['costcredit'] . '积分', $activity['merchantid']);
                    }
                }

                //生成核销码、二维码
                //$listNum = pdo_fetchall("SELECT hexiaoma as num FROM " . tablename ('aide_activity_records') . " WHERE activityid = $activityid");
                //$ma['hexiaoma'] = createNumber($listNum);
                $ma['hexiaoma'] = $data['hexiaoma'] = createRandomNumber(8);
                pdo_update('aide_activity_records', $ma, array('id' => $recordid, 'uniacid' => $_W['uniacid']));
                createQrcode::creategroupQrcode($data['orderno']);
//				if (!$activity['hasreview']) {//活动不开启审核发送通知
//					//报名成功通知
//					message::join_success($_W['openid'], $activity, $recordid, app_url('records/records/list'));
//					if($activity['smsswitch']){//短信通知
//						$smsparams=array(
//							'product' => $_W['_config']['sname'],
//							'item'    => $activity['title'],
//							'name'    => $data['realname'],
//							'timestr' => date('m月d日 H:i',strtotime($activity['starttime'])),
//							'idcode'  => $data['hexiaoma']
//						);
//						$template_id = empty($activity['smsnotify']) ? $_W['_config']['sms_notify'] : $activity['smsnotify'];
//						sendSMS($data['mobile'], $smsparams, $template_id, $_W['_config']['sms_type']);
//					}
//				}else{
//					//审核通知
//					message::join_review($_W['openid'], $activity, 2, app_url('records/records/list'));
//				}
                if ($_W['_config']['mmsg']){//管理通知
                    if ($activity['merchantid']) $merchant = model_merchant::getSingleMerchant($activity['merchantid'], '*');//读取主办方
                    $openids = unserialize($activity['openids']);
                    $openids = !empty($openids) ? $openids : unserialize($merchant['messageopenid']);
                    $openids = !empty($openids) ? $openids : $_W['_config']['openids'];
                    if (!empty($openids)){
                        foreach($openids as $key=> $value){
                            message::admin_notice($value, $activity, $recordid, '');
                        }
                    }
                }

                die(json_encode(array('errno' => 0, 'recordid' => $recordid)));
                exit;
            }
        }

    }
}

if($_W['isajax'] && $op =='validquota'){//验证名额填写时的剩余名额；
    if ($quota > 0){
        if($joinnum >= $quota) {
            die(json_encode(array('errno'=>1,'message'=>"很遗憾！名额已经满了")));
        }elseif($joinnum + $teamnum > $quota){
            die(json_encode(array('errno'=>1,'message'=>"当前活动仅剩 " . ($quota - $joinnum) . ' 个名额')));
        }
    }
    die(json_encode(array('errno'=>0)));
}

//人脸上传
if($op=='faceimgupload'){
    if($activity['has_record_image'] == 1){
        $file = $_FILES['jianlu'];
        $file_name = str_pad(date('dHis',time()),8,'9',STR_PAD_LEFT).str_pad(rand(0,99),2,'0',STR_PAD_LEFT);
        $upload = file_upload2($_W['uniacid'], $file, $file_name);
        if(is_error($upload)){
            $out = array(
                'errno' => 1,
                'errmsg' => $upload['message']
            );
            echo json_encode($out);exit;
        }else{
            $insert_data = array(
                'uniacid' => $_W['uniacid'],
                'activityid' => $activity['id'],
                'openid' => $_W['openid'],
                'file_name' => $file_name,
                'file_path' => '/addons/aide_activity' . $upload['path']
            );
            $res = pdo_insert("aide_faceimg", $insert_data);
            if($res){
                $faceimg_id = pdo_insertid();
                //百度人脸识别
                $model_baidu = new model_baidu();
                $file_path = IA_ROOT . '/addons/aide_activity' . $upload['path'];
                $faceRes = $model_baidu->checkPictureToCheckFace($file_path);
                //人脸不通过，返回错误，并删掉数据和图片
                if($faceRes['result'] != true){
                    pdo_delete('aide_faceimg', array('id'=>$faceimg_id));
                    unlink($file_path);
                    $out = array(
                        'errno' => 1,
                        'errmsg' => $faceRes['err_msg']
                    );
                    echo json_encode($out);exit;
                }
                //上传成功，删除旧数据
                if($_GPC['faceimg_id'] > 0){
                    $condition = array(
                        'id' => $_GPC['faceimg_id'],
                        'uniacid' => $_W['uniacid'],
                        'activityid' => $activity['id'],
                        'openid' => $_W['openid']
                    );
                    $old = pdo_get('aide_faceimg', $condition);
                    if($old){
                        pdo_delete('aide_faceimg', array('id'=>$old['id']));
                        $file = IA_ROOT . $old['file_path'];
                        unlink($file);
                    }
                }
            }else{
                $out = array(
                    'errno' => 1,
                    'errmsg' => '上传保存失败'
                );
                echo json_encode($out);exit;
            }
            $data = array(
                'faceimg_id' => $faceimg_id,
                'file_name' => $file_name,
                'file_path' => '/addons/aide_activity' . $upload['path']
            );
            $out = array(
                'errno' => 0,
                'errmsg' => 'ok',
                'data' => $data
            );
            echo json_encode($out);exit;
        }
    }
}

function file_upload2($uniacid,$file,$attname='', $name = '') {
    load()->func('file');
    if(empty($file)) {
        return error(-1, '没有上传内容');
    }
    $deftype = array('png','jpg');
    $extention = pathinfo($file['name'], PATHINFO_EXTENSION);
    if(!in_array(strtolower($extention), $deftype)) {
        return error(-1, '不允许上传此类文件');
    }
    $result = array();

    if(empty($name) || $name == 'auto') {
        $result['path'] = "/uploadfile/".$uniacid."/". date('Ym') . '/';
        mkdirs(MODULE_ROOT . $result['path']);
        do {
            if(empty($attname)){
                $nowname = random(20);
                $filename =  $nowname. ".{$extention}";
            }else{
//                $file['name'] = str_replace(".".$extention,'',$file['name']);
//                $filename = $file['name'] .random(2). ".{$extention}";
                $nowname = $attname;
//                $filename = $attname . ".{$extention}";
                $filename = $attname . ".jpg";
            }
        } while(file_exists(MODULE_ROOT . $result['path'] . $filename));
        $result['path'] .= $filename;
    } else {
        $result['path'] = $name . '.' .$extention;
    }

    if(!file_move($file['tmp_name'], MODULE_ROOT . '/' . $result['path'])) {
        return error(-1, '保存上传文件失败');
    }
    $result['nowname'] = $nowname;
    $result['success'] = true;
    return $result;
}
function updateOrInsert($table,$data,$where=''){
    if (empty($where)){
        pdo_insert($table,$data);
        return pdo_insertid();
    }else{
        $result=pdo_update($table,$data,$where);
        if (!empty($result)){
            return $where;
        }else{
            pdo_insert($table,$data);
            return pdo_insertid();
        }
    }
}
